<template>
  <div class="file">
    <div class="table-container">
      <vxe-grid
        border
        show-overflow
        resizable
        ref="fileTableRef"
        class="vxe-table-element"
        size="mini"
        align="center"
        :auto-resize="true"
        :data="tableData"
        :cell-style="cellStyle"
        @cell-click="cellClick"
        :toolbar="{}"
        :valid-config="{ autoPos: true, message: 'inline' }"
        @select-change="handleSelectionChange"
        @select-all="handleSelectionChange"
        height="200"
      >
        <template v-slot:buttons>
          <template v-if="isShowDownBtn">
            <el-button
              @click="downAllBtnClickHandler"
              size="small"
              type="primary"
              class="vxe-btn-delete"
              style="margin-right: 10px"
              >批量下载</el-button
            >
          </template>
          <template v-else>
            <!-- <IELUploadBtn
              @upload="uploadHandler"
              v-bind="$attrs"
              v-on="$listeners"
              v-if="!isDisabledUpload || !isDisabledUploadBtnByTableData"
              :isDisabledUpload="isDisabledUpload || isDisabledUploadBtnByTableData"
            /> -->
            <el-button
              @click="openUploadHandler"
              type="primary"
              v-if="!isDisabledUpload || !isDisabledUploadBtnByTableData"
              >上传</el-button
            >
            <el-button
              @click="deleteBtnClickHandler"
              size="small"
              type="danger"
              class="vxe-btn-delete"
              v-if="!isDisabledDelete"
              :disabled="isDisabledDelete"
              style="margin-right: 10px"
              >删除</el-button
            >
            <el-button
              @click="downAllBtnClickHandler"
              size="small"
              type="primary"
              class="vxe-btn-delete"
              style="margin-right: 10px"
              :disabled="isDisabledDelete"
              >批量下载</el-button
            >
          </template>
        </template>
        <vxe-table-column type="checkbox" width="50" fixed="left"> </vxe-table-column>
        <vxe-table-column type="seq" title="序号" width="60"></vxe-table-column>
        <vxe-table-column
          v-for="(item, index) in tableColumnList"
          :key="index"
          :type="item.type"
          :fixed="item.fixed"
          :field="item.field"
          :title="item.title"
          :width="item.width"
          :sortable="item.sortable"
        >
          <template v-slot="{ row }">
            <span v-if="item?.field == 'gmtCreate'">{{ formatDateStr(row[item.field]) }}</span>
            <span v-else-if="item.field === 'operation'">
              <el-button type="text" @click="() => openViewHandler(row)">查看</el-button>
            </span>
            <span v-else>{{ row[item.field] }}</span>
          </template>
        </vxe-table-column>
      </vxe-grid>
    </div>
    <ViewFile ref="viewFileRef" />
    <!-- 上传弹框组件 -->
    <UploadDialog
      ref="uploadDialogRef"
      @upload="uploadHandler"
      v-bind="$attrs"
      v-on="$listeners"
      :isDisabledUpload="isDisabledUpload || isDisabledUploadBtnByTableData"
    />
  </div>
</template>

<script>
import { formatDate } from '@/utils';
import API from '@/api/dataBase';
import ViewFile from './../ViewFile';
import UploadDialog from './../UploadDialog';
export default {
  name: 'FileTable',
  props: {
    // 上传文件列表反填到表格中
    attachments: {
      type: Array,
      default: () => [],
    },
    // 是否显示下载按钮
    isShowDownBtn: {
      type: Boolean,
      default: false,
    },
    // 是否禁用删除按钮
    isDisabledDelete: {
      type: Boolean,
      default: false,
    },
    // 是否禁用上传按钮
    isDisabledUpload: {
      type: Boolean,
      default: false,
    },
    // 文件数量,0表示不限制文件数量
    limitFileCount: {
      type: Number,
      default: 0,
    },
    // 是否解析成不同的链接跳转，目前只有多联订单用到
    showLinks: {
      type: Boolean,
      default: false,
    },
    cellStyle: {
      type: Function,
      default: () => {},
    },
    cellClick: {
      type: Function,
      default: () => {},
    },
  },
  data() {
    return {
      actionUrl: '',
      tableData: [],
      selectionList: [],
      tableColumnList: [
        {
          field: 'attachmentName',
          title: '附件名称',
        },
        {
          field: 'createBy',
          title: '上传人',
        },
        {
          field: 'gmtCreate',
          title: '上传时间',
        },
        { field: 'operation', title: '操作' },
      ],
      isDisabledUploadBtnByTableData: false,
    };
  },
  methods: {
    // 打开上传面板
    openUploadHandler() {
      console.log('打开');
      this.$refs.uploadDialogRef.openDialog();
    },
    openViewHandler(rowItem) {
      this.$refs.viewFileRef.openViewHandler(rowItem);
    },
    disabledUploadBtnHandler() {
      if (this.limitFileCount > 0) {
        this.isDisabledUploadBtnByTableData =
          this.limitFileCount - 1 <= this.$refs.fileTableRef.getTableData().fullData.length;
      } else {
        this.isDisabledUploadBtnByTableData = false;
      }
    },
    handleSelectionChange({ selection }) {
      console.log(selection, '选择行');
      this.selectionList = selection;
    },
    formatDateStr(item) {
      return formatDate(item);
    },
    deleteBtnClickHandler() {
      if (!this.selectionList.length) {
        this.$message.error('请选择行操作');
        return;
      }
      const xIDList = this.selectionList.map((item) => item._XID);
      this.tableData = this.tableData.filter((item) => !xIDList.includes(item._XID));
      this.disabledUploadBtnHandler();
    },
    // 批量下载
    downAllBtnClickHandler() {
      if (this.selectionList.length === 0) {
        this.$message({
          showClose: true,
          message: this.$t('upload.noSelectDownLoad'),
          type: 'error',
        });
      } else {
        let params = {
          keyList: this.selectionList.map((it) => it.attachmentKey),
        };
        this.$axios.post(API.DOWNLOAD_FILE, params).then((res) => {
          if (res.data.code == 0) {
            res.data.data.forEach((it) => {
              this.downloadFile(it);
            });
          }
        });
      }
    },
    //多个文件下载
    downloadFile(url) {
      window.open(url, '_blank');
    },
    // 上传成功回调
    uploadHandler(fileObj) {
      this.tableData.push({
        attachmentName: fileObj.attachmentName,
        createBy: fileObj.createBy,
        gmtCreate: new Date(),
        attachmentKey: fileObj.attachmentKey,
        // attachmentId: fileObj.attachmentId,
        attachmentPath: fileObj.attachmentPath,
      });
      this.disabledUploadBtnHandler();
    },
    getTableData(isFormatData = true) {
      const $table = this.$refs.fileTableRef;
      if (isFormatData) {
        const tableData = this.tableData;
        return tableData.map((item) => {
          return {
            ...item,
            gmtCreate: this.formatDateStr(item.gmtCreate),
          };
        });
      } else {
        return $table.getTableData().fullData;
      }
    },
    // 填充表格数据
    fullTableData(val) {
      this.tableData = val;
    },
  },
  watch: {
    attachments: {
      handler(val) {
        if (val && Array.isArray(val) && val.length) {
          this.fullTableData(val);
          this.disabledUploadBtnHandler();
        }
      },
      immediate: true,
      deep: true,
    },
  },
  components: {
    ViewFile,
    UploadDialog,
  },
};
</script>

<style lang="scss" scoped>
.file {
  background: #fff;
  .table-container {
    padding: 10px;
    box-sizing: border-box;
    padding-top: 0;
  }
}
</style>
